package com.hci.pwf;

import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;

import com.google.android.maps.GeoPoint;

public class LocationUtil {

	public static String getBestProvider(LocationManager lm) {

		Criteria mCriteria = new Criteria();
		mCriteria.setAccuracy(Criteria.ACCURACY_FINE);
		mCriteria.setAltitudeRequired(false);
		mCriteria.setBearingRequired(false);
		mCriteria.setCostAllowed(true);
		mCriteria.setPowerRequirement(Criteria.POWER_LOW);
		String strLocationProvider = lm.getBestProvider(mCriteria, true);

		return strLocationProvider;
	}

	public static Location getLocationProvider(LocationManager lm) {
		Location location = lm.getLastKnownLocation(LocationUtil.getBestProvider(lm));
		return location;

	}

	public static GeoPoint getGeoByLocation(Location location) {

		GeoPoint gp = null;
		try {
			if (location != null) {
				double geoLatitude = location.getLatitude() * 1E6;
				double geoLongitude = location.getLongitude() * 1E6;
				gp = new GeoPoint((int) geoLatitude, (int) geoLongitude);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return gp;
	}

	public static Address getAddressbyGeoPoint(Context cntext, GeoPoint gp) {

		Address result = null;
		try {
			if (gp != null) {
				Geocoder gc = new Geocoder(cntext, Locale.getDefault());

				double geoLatitude = (int) gp.getLatitudeE6() / 1E6;
				double geoLongitude = (int) gp.getLongitudeE6() / 1E6;

				List<Address> lstAddress = gc.getFromLocation(geoLatitude,
						geoLongitude, 1);

				if (lstAddress.size() > 0) {
					result = lstAddress.get(0);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

}
